package cn.openea.perpartner.mpwx.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.openea.perpartner.mpwx.core.SendMsgTemplate;
import cn.openea.perpartner.mpwx.core.WxServiceTemplate;
import cn.openea.perpartner.mpwx.entity.MagmasMsg;
import cn.openea.perpartner.mpwx.mapper.MagmasMsgMapper;
import cn.openea.perpartner.mpwx.service.IMagmasMsgService;
import cn.openea.perpartner.system.entity.SysUser;
import cn.openea.perpartner.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;


/**
 * @author Weird077
 * @description TODO
 * @date 2022-06-21 23:37
 */
@Service
public class MagmasMsgServiceImpl implements IMagmasMsgService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private MagmasMsgMapper magmasMsgMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private WxServiceTemplate wxServiceTemplate;
    @Autowired
    private SendMsgTemplate sendMsgTemplate;
    private  String servermark;
    @Value("${applet.unifiedURI}")
    private String unifiedURI;


    @PostConstruct
    public void init(){
        sendMsgTemplate.setWxMpService(wxServiceTemplate.getWxMpService());
        servermark = "dev".equals(active)?"【体验版】":"";
    }
    @Override
    public String sendTextMsg(String toWxOpenid, String textmsg) {
        JSONObject msgobj = new JSONObject();
        msgobj.put("touser", toWxOpenid);
        msgobj.put("msgtype", "text");
        JSONObject textobj = new JSONObject();
        textobj.put("content", textmsg);
        msgobj.put("text", textobj);
        return sendMsgTemplate.sendMsg(msgobj, "text");
    }

    @Override
    public String sendTemplateMsg(String docUnid) {
        // 通过文档id，查到当前文档的用户，主要是想知道要将消息发送给谁
        String userid =  magmasMsgMapper.selectById(docUnid).getUserid();
        // 再通过社区id，获取用户关注公众号时的openid，此时就可以知道要发送给谁了
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserid,userid);
        String toWxOpenid = userMapper.selectOne(wrapper).getMyopenid().trim();
        if(StrUtil.isBlank(toWxOpenid)){
            logger.debug("errmsg=在记录中未匹配到接收者的身份");
            return "{\"errcode\":-1,\"errmsg\":\"在记录中未匹配到接收者的身份\"}";
        }
        return sendTemplateMsg(toWxOpenid, docUnid);
    }

    @Override
    public String sendTemplateMsg(String toWxOpenid, String docUnid) {
        // 通过文档id，查到当前文档的记录
        MagmasMsg magmasMsg = magmasMsgMapper.selectById(docUnid);
        logger.debug("doc="+magmasMsg.toString());
        // 需要发送的模板id
        String template_id = magmasMsg.getTemplateid();
        // 模板跳转链接
        String url = magmasMsg.getUrl();
        // 所需跳转到的小程序信息
        JSONObject miniappdata = new JSONObject();
        if(StrUtil.isNotBlank(magmasMsg.getMiniappid()) && StrUtil.isNotBlank(magmasMsg.getPagepath())){
            miniappdata.put("appid", magmasMsg.getMiniappid());
            // 20220214 Add 这里地址不为空时，用于跳转到统一通知调用地址，这里是依据消息应用配置 unifiedURI 值判断的
            String pagepath = magmasMsg.getPagepath() ;
            if(StrUtil.isNotBlank(unifiedURI)){
                pagepath = unifiedURI + docUnid;
            }
            pagepath = URLUtil.decode(pagepath);
            // 实际地址的参数，官方文档写的pagepath可能不起作用
            miniappdata.put("path", pagepath);
            // 微信官方文档写的内容，实际可能不起作用，这里为能两个都写上，否则会出 invalid weapp pagepath rid
            miniappdata.put("pagepath", pagepath);
        }
        // 消息的业务主体内容
        JSONObject msgdata = new JSONObject();
        msgdata.put("first", getJsonData(servermark + magmasMsg.getFirst(), ""));
        msgdata.put("keyword1", getJsonData(magmasMsg.getKeyword1(), ""));
        msgdata.put("keyword2", getJsonData(magmasMsg.getKeyword2(), ""));
        msgdata.put("keyword3", getJsonData(magmasMsg.getKeyword3(), ""));
        msgdata.put("keyword4", getJsonData(magmasMsg.getKeyword4(), ""));
        msgdata.put("keyword5", getJsonData(magmasMsg.getKeyword5(), ""));
        msgdata.put("keyword6", getJsonData(magmasMsg.getKeyword6(), ""));
        msgdata.put("remark", getJsonData(magmasMsg.getRemark(), ""));
        // 执行发送消息
        return sendTemplateMsg(toWxOpenid, template_id, url, miniappdata, msgdata);
    }

    @Override
    public String sendTemplateMsg(String toWxOpenid, String templateId, String url, JSONObject miniappdata, JSONObject msgdata) {
        // 组装需要发送的消息
        JSONObject msgobj = new JSONObject();
        msgobj.put("touser", toWxOpenid);
        msgobj.put("template_id", templateId);
        // 模板跳转链接（海外帐号没有跳转能力）
        if(StrUtil.isNotBlank(url)){
            msgobj.put("url", url);
        }
        // 跳小程序所需数据，不需跳小程序可不用传该数据，包含appid和pagepath的JSON串
        if(null != miniappdata){
            msgobj.put("miniprogram", miniappdata);
        }
        msgobj.put("data", msgdata);
        return sendMsgTemplate.sendMsg(msgobj, "template");
    }

    @Override
    public String sendTemplateMsg(String toWxOpenid, String templateId, JSONObject miniappdata, JSONObject msgdata) {
        return sendTemplateMsg(toWxOpenid, templateId, null, miniappdata, msgdata);
    }

    @Override
    public String sendTemplateMsg(String toWxOpenid, String templateId, String url, JSONObject msgdata) {
        return sendTemplateMsg(toWxOpenid, templateId, url, null, msgdata);
    }

    @Override
    public String sendTemplateMsg(String toWxOpenid, String templateId, JSONObject msgdata) {
        return sendTemplateMsg(toWxOpenid, templateId, null, null, msgdata);
    }
    private JSONObject getJsonData(String value, String color) {
        if(StrUtil.isBlank(color)){
            color = "#173177";
        }
        JSONObject object = new JSONObject();
        object.put("value", value);
        object.put("color", color);
        return object;
    }
}
